<template>
  <div class="vue-tree pl-15">
    <div class="vue-cell">
      <div class="vue-cell__title" @click="clickTree(data)">
        {{ data[defaults.name] }}
      </div>
      <i
        v-if="hasChild"
        :class="'x_y_center van-icon van-icon-arrow-' + (open ? 'up' : 'down')"
        @click="open = !open"
      ></i>
    </div>
    <transition name="van-slide-down">
      <div v-show="open" v-if="hasChild">
        <tree-item
          @click="clicks"
          v-for="item in data[defaults.children]"
          :data="item"
          :key="item[defaults.id]"
          :defaults="defaults"
        ></tree-item>
      </div>
    </transition>
  </div>
</template>

<script>
export default {
  name: "TreeItem",
  props: {
    data: {
      type: [Object, Array],
      required: true,
    },
    defaults: {
      type: Object,
      default: () => {
        return {
          id: "id",
          name: "name",
          children: "children",
        };
      },
    },
  },
  data() {
    return {
      open: false,
    };
  },
  created() {},
  mounted() {},
  computed: {
    hasChild() {
      return this.data.children && this.data.children.length;
    },
  },
  methods: {
    // 下拉还是选中
    clickTree(data) {
      if (data.children && this.data.children.length) {
        return (this.open = !this.open);
      }
      this.$emit("click", data);
    },
    // 点击事件
    clicks(data) {
      this.$emit("click", data);
    },
  },
};
</script>

<style>
.x_y_center {
  display: flex;
  align-items: center;
  justify-content: center;
}
.pl-15 {
  padding-left: 15px;
}
.vue-tree {
  overflow: hidden;
}
.vue-tree .vue-cell {
  padding: 5px 15px 5px 0;
  border-bottom: 1px dashed #ddd;
  position: relative;
  display: flex;
  box-sizing: border-box;
  width: 100%;
  overflow: hidden;
  color: #323233;
  font-size: 0.373333rem;
  line-height: 0.64rem;
  background-color: #fff;
  z-index: 9;
}
.vue-tree .vue-cell .van-icon {
  font-size: 18px;
}
.vue-tree .vue-cell .vue-cell__title {
  min-height: 18px;
}
.vue-tree .vue-tree .vue-cell .vue-cell__title {
  min-height: 0.48rem;
}
.vue-tree .vue-cell__title,
.vue-tree .vue-cell__value {
  flex: 1;
}
</style>
